<?php

/*
 * 管理Customer的Action
 * 
 */
class CustomerAction extends Action {
	/*
	 * 显示当前所有客户，登录Customer必须为0，否则返回当前客户
	 */
	public function index($order="id",$orderBy="desc",$start=0,$limit=25){
        /**
         * LLyeap_wx_customer修改
         */
		$Customer = D("Customer");
        $IndMediaInfo_Model = D('ind_media_info');

		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		/** 这里这个筛选过滤, 都是用户层, 不是自媒体账号层, 所以都是用isDefault来过滤, 不用mediaId */
		if (Session::$user["customerId"] != 0) {
            /***** LLyeap_delete *****/
//			$condition = "id='" . Session::$user["customerId"] . "'";
            /*****  *****/

            $condition = ['cid' => Session::$user["customerId"], 'isDefault' => 1];
//			$result = $Customer->where($condition)->select();
			$result = $IndMediaInfo_Model->where($condition)->select();
		} else {
//			$condition = "id <> 0";
			$condition = ['isDefault' => 1];
//			$result = $Customer->where($condition)->order("$order $orderBy")->limit("$start,$limit")->select();
			$result = $IndMediaInfo_Model->where($condition)->order("$order $orderBy")->limit("$start,$limit")->select();
		}
		
		if (!isset($result)) {
			Output::instance()->resultCode(code_success, "未找到客户");
			return;
		}
		
//		$count = $Customer->where($condition)->count();
		$count = $IndMediaInfo_Model->where($condition)->count();
		Output::instance()->objArray($result, $count);
	}

	/*
	 * 获取uuid或者token信息
	*/
	public function getCustomerInfo($cid=null, $mediaId = 0){
		//不切换数据库
        /**
         * 这里通过id(cid)查询wx_customer信息
         * LLyeap_wx_customer修改
         */
//		$customer = D('customer');
		$IndMediaInfo_Model = D('ind_media_info');

		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$cid     = ($cid == null) ? Session::$user["customerId"] : $cid;
        if ($mediaId > 0) { // 如果拿到了$mediaId, 则通过id来筛选
            $where_info = ['imi.cid' => $cid, 'imi.id' => $mediaId];
        } else {        // 如果没有$mediaId, 则拿这个cid下默认的账号, 即default = 1的, 只有一个
            $where_info = ['imi.cid' => $cid, 'imi.isDefault' => 1];
        }
        /***** LLyeap_delete *****/
//		if($cid == null){
//			$where['id'] = Session::$user["customerId"] ;
//		}else{
//			$where['id'] = $cid;
//		}
//		$result = $customer->where($where)->find();
        /*****  *****/

        // 注意, 这里数据是返回给前端使用, 这里不知道使用了哪些内容, 所以我尽量保持数据一致
        $result = $IndMediaInfo_Model
            ->alias('imi')
            ->where($where_info)
            ->join('left join wx_customer c ON c.id = imi.cid')
            ->field('c.role, imi.id as mediaId, imi.cid as id, imi.uuid, imi.token, imi.expired, imi.appid, imi.appsecret, 
            imi.accessToken, imi.accessExpiration, imi.isApiAuth, imi.isAutoGroup, imi.wxAppAppid, imi.wxAppSecret, imi.wxAppAccessToken,
            imi.wxAppAccessExpiration, imi.mode, imi.refreshToken, imi.third_platform_appid')
            ->find();
        \Log::write('lilei_CustomerAction::getCustomerInfo_' . $IndMediaInfo_Model->getLastSql());
	
// 		Log::write('getCustomerInfo sql:'.$customer->getLastSql());
		if (!isset($result)) {
			Output::instance()->resultCode(code_user_not_exist);
			return;
		}
	
		Output::instance()->object($result);
	}
	
	
	/*
	 * 重置uuid和Token
	 * 需登录，登录Customer只能修改自己的
	 */
	public function reset($cid, $mediaId = 0){
		$retVal = Session::init();
		if (!$retVal || Session::$user["customerId"] != $cid) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		
//		$Customer = D("Customer");
//		$Customer->uuid = Encryption::c_uuid();
//		$Customer->token = Encryption::token();
        $IndMediaInfo = D('ind_media_info');
        $data['uuid']   = Encryption::c_uuid();
        $data['token']  = Encryption::token();

//        $where['id'] = cid;
//        $Customer->$where($where)->save();

        if ($mediaId > 0) { // 如果拿到了$mediaId, 则通过id来筛选
            $where_info = ['imi.cid' => $cid, 'imi.id' => $mediaId];
        } else {        // 如果没有$mediaId, 则拿这个cid下默认的账号, 即default = 1的, 只有一个
            $where_info = ['imi.cid' => $cid, 'imi.isDefault' => 1];
        }
        $IndMediaInfo->where($where_info)->save($data);
		
//		$result = $Customer->$where($where)->find();
        $result = $IndMediaInfo->where($where_info)->find();
		Output::instance()->object($result);
	}
	
	/*
	 * 更新客户信息
	 * 需登录，Customer为当前客户，则可以修改fullName，为0，则可以修改过期时间
	 */
	public function update($cid) {
		throw_exception("未实现接口");
	}
	
	/*
	 * 删除用户信息
	 * 需登录，登录CustomerId必须为0
	 */
	public function delete($cid) {
		throw_exception("未实现接口");
	}

	//用户进入专属页面的时候,将平台信息返回。包括平台名称，logo，二维码。
    public function qrcodeLoginInfo($cid){
   		 /**1.参数获取*/
        $customerId = $cid;

   		 /**2.数据库模型*/
        /**
         * 这块内容放在用户里
         * 20170713 - 这块内容不移动到wx_ind_media_info中, 所以这里不需要修改
         * LLyeap_wx_customer修改
         */
        $customer = M('customer');
        $customer_user = M("customer_user");

   		 /**3.数据查询*/
        $customerInfo = $customer->field('qrcodeLogin,brandName,brandLogoUrl')->where("id=$customerId")->find();

   		 /**4.数据返回*/
        if ($customerInfo['qrcodeLogin']){
            $name=$customer_user->field('fullname')->where("customerId=$customerId")->find();
            $fullname = $name['fullname'];
            $time = date('Y-m-d H:i:s',time());
            $data = QRCode::add("登录_".$fullname.'_'.$time, null,"qrcode", '', "login",QR_SCENE, '', '', $customerId);
            $return['code'] = 0;
            $return['brandName'] = $customerInfo['brandName'];
            $return['brandLogoUrl'] = $customerInfo['brandLogoUrl'];
            $return['qrcodeUrl'] = $data['img'];
            $return['customerId'] = $data['fromCustomerId'];
            $return['ticket'] = $data['ticket'];
            Output::instance()->object($return);
        }else{
            $return['code'] = 1;
            $return['msg'] = '平台没有开启二维码登录权限';
            $return['data'] = [
            	'brandName' =>$customerInfo['brandName'],
            	'brandLogoUrl'=>$customerInfo['brandLogoUrl']

            ];
            Output::instance()->object($return);
        }
    }
	//判断是否拥有二维码登录权限，两种情况。（参数cid可从session中获得，status参数负责区分是开启还是关闭二维码登录）
    public function qrcodeLoginPower($status){ 
   		 /**1.判断用户是否登录*/
		 $retVal = Session::init();
		 if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		 }
		/**2. 判断是不是平台管理员 */
        $isBusiness = Session::isBusiness();
        if (!$isBusiness) {
            Output::instance()->resultCode(code_user_priv_invalid);
            return;
        }

   		 /**3.数据表模型*/
        $customerId = session::$user['customerId'];
        $mediaId    = Session::$user['mediaId'];
        Session::switchCustomer(0);
        /** 这里下面绑定开通了二维码扫码登录之后, 需要修改customer内容, 所以这里不能删除这个model */
        $customer = M("customer");
        $IndMediaInfo_Model = M('ind_media_info');
        $weixin = M('customer_weixin_profile');
        Session::switchCustomer($customerId);

   		 /**4.逻辑处理，数据返回*/
         //根据状态参数区分是开启还是关闭二维码登录
		 if($status == 1){
	         //1.customer表查看是否满足具有appid、appsecret、isApiAuth
             /***** LLyeap_delete *****/
//	    	 $result=$customer->field('appid,appsecret,isApiAuth')->where("id=$customerId")->find();
             /*****  *****/

             if ($mediaId) { // 如果拿到了$mediaId, 则通过id来筛选
                 $where_info = ['cid' => $customerId, 'id' => $mediaId];
             } else {        // 如果没有$mediaId, 则拿这个cid下默认的账号, 即default = 1的, 只有一个
                 $where_info = ['cid' => $customerId, 'isDefault' => 1];
             }
             $result = $IndMediaInfo_Model->where($where_info)->field('appid, appsecret, isApiAuth')->find();

	    	 //2.customer_weixin_profile表查看是否授权
	    	 $grant = $weixin->field('grantstatus')->where("cid=$customerId")->find();
	    	 if ($result['appid']&&$result['appsecret']&&$result['isApiAuth']){
	    	 	$data['qrcodeLogin'] = 1;
		        $customer->where("id=$customerId")->save($data);
	    	 	$return['code'] = 0;
	    	 	$return['msg'] = '恭喜您开启二维码登录成功';
	    	 	Output::instance()->object($return);
	    	 }else if($grant['grantstatus']){
	    	 	$data['qrcodeLogin'] = 1;
		        $customer->where("id=$customerId")->save($data);
	    	 	$return['code'] = 0;
	    	 	$return['msg'] = '恭喜您开启二维码登录成功';
	    	 	Output::instance()->object($return);

	    	 }else{
	    	 	$return['code'] = 1;
	    	 	$return['msg'] = '您没有开启权限';
	    	 	Output::instance()->object($return);

	    	 } 
		 }else{
	        $data['qrcodeLogin'] = 0;
	        $result = $customer->where("id=$customerId")->save($data);
	        if ($result !== false){
	        	$content_sql = $customer->getLastSql();
	        	R('Log/add',array('accessControl','130','访问控制',op_update,$content_sql,'开启平台扫码登录'));
	        	$return['code'] = 0;
	    	 	$return['msg'] = '关闭二维码登陆成功，可随时开启哦';
	    	 	Output::instance()->object($return);
	        }else{
	        	$return['code'] = 1;
	    	 	$return['msg'] = '关闭失败，请重试';
	    	 	Output::instance()->object($return);
	        }
		 }
       	 
    }

    //保存登录专属页面信息,需要平台名称还有图片路径两个参数。
    public function loginConfig($name,$logo){
   		 /**1.判断用户是否登录*/
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		/**2. 判断是不是平台管理员 */
        $isBusiness = Session::isBusiness();
        if (!$isBusiness) {
            Output::instance()->resultCode(code_user_priv_invalid);
            return;
        }

   		 /**3.数据库模型*/
    	$customerId = session::$user['customerId'];
    	Session::switchCustomer(0);
        /** 这里对绑定二维码登录操作进行相关数据修改, 内容都在wx_customer表里 */
        $customer = M("customer");
        $weixin = M("customer_weixin_profile");
        Session::switchCustomer($customerId);

        /**4.数据保存*/
        $data['brandName'] = $name;
        $data['brandLogoUrl'] = $logo;
        $result = $customer->where("id=$customerId")->save($data);
        
        /**5.数据返回*/
        if ($result !== false){
        	$content_sql = $customer->getLastSql();
	        R('Log/add',array('accessControl','130','访问控制',op_update,$content_sql,'保存登录专属页面信息'));
        	$return['code'] = 0;
    	 	$return['msg'] = '恭喜您登录页专属信息保存成功';
    	 	Output::instance()->object($return);
        }else{
        	$return['code'] = 1;
    	 	$return['msg'] = '登录页专属信息保存失败，请重试';
        	Output::instance()->object($return);
        }
    } 

   	//判断平台之前是否开启二维码登录
	public function getQRcodeLoginStatus()
	{
		/**1.判断用户是否登录*/
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		/**2.数据表模型*/
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$customer = M('customer');
		Session::switchCustomer($customerId);


		/**3.数据获取*/
		$customerInfo = $customer->field('qrcodeLogin,brandName,brandLogoUrl')->where("id=$customerId")->find();
		if ($customerInfo['qrcodeLogin']){
			$return['code'] = 0;
    	 	$return['msg'] = '已开启';
    	 	$return['data'] =[
    	 	    'brandName' =>  $customerInfo['brandName'],
    	 	    'brandLogoUrl' =>  $customerInfo['brandLogoUrl']
            ];
    	 	Output::instance()->object($return);
    	 }else{
    	 	$return['code'] = 1;
    	 	$return['msg'] = '未开启';
            $return['data'] =[
                'brandName' =>  $customerInfo['brandName'],
                'brandLogoUrl' =>  $customerInfo['brandLogoUrl']
            ];
    	 	Output::instance()->object($return);
    	 }
	}


}